package com.keeson.android_cli.base;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.gyf.immersionbar.ImmersionBar;
import com.keeson.android_cli.commom.EventCode;
import com.keeson.android_cli.manager.ActivityManager;
import com.keeson.android_cli.ui.main.TokenExpireDialog;
import com.keeson.android_cli.util.AppUtils;
import com.keeson.android_cli.util.BindingUtil;
import com.keeson.android_cli.util.EventBusUtils;
import com.keeson.android_cli.util.StringUtils;
import com.keeson.android_cli.util.ToastUtils;
import com.keeson.android_cli.util.UIHelper;
import com.keeson.android_cli.util.uifactory.Axis;
import com.keeson.android_cli.widget.CommonDialog;
import com.keeson.android_cli.widget.LoadingDialog;
import com.keeson.android_cli.widget.ShowDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by jiaqiZHou
 * on 2020/12/4
 */
public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity {
    protected static final int REQ_FILE_CHOOSE = 0x01;
    protected T binding;
    private LoadingDialog mLoadingDialog;
    private ShowDialog showDialog;
    public Context context;
    private boolean isInit = false;
    public CompositeDisposable mCompositeDisposable;
    private static BaseActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        beforeShow(savedInstanceState);
        binding = BindingUtil.createBinding(this);
        if (binding == null) {
            throw new NullPointerException("binding is null");
        }
        setContentView(((ViewBinding) binding).getRoot());
        if (!isInit) {
            isInit = true;
            Axis.init(this,1080,1920);//适配初始化,基准宽高
        }
        context = this;

        //初始化沉浸式
        initImmersionBar();
        if (isRegisterEventBus()) {
            EventBusUtils.register(this);
        }
        ActivityManager.getInstance().addActivity(this);
        initBasePresenter();
        initCreate(savedInstanceState);
        initView();
        initData();
        initListener();
    }


    /**
     * 添加订阅
     */
    public void addDisposable(Disposable mDisposable) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(mDisposable);
    }
    /**
     * 取消所有订阅
     */
    public void clearDisposable() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
        }
    }


    public void initCreate(Bundle savedInstanceState) {

    }

    public void initBasePresenter() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().removeActivity(this);
        if (isRegisterEventBus()) {
            EventBusUtils.unregister(this);
        }
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }

        if (showDialog != null) {
            showDialog.dismiss();
            showDialog = null;
        }

        clearDisposable();

    }



    /**
     * 在显示之前   getIntent啊 等等
     *
     * @param savedInstanceState
     */
    public  void beforeShow(Bundle savedInstanceState){

    };


    public abstract void initView();

    public void initData() {

    }

    public void initListener() {

    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(BaseEvent event) {
        if (event != null) {
            switch (event.getCode()) {
                case EventCode.EVENT_TOKEN_EXPIRE:
                        UIHelper.toActivityCommon(context, TokenExpireDialog.class);
                    break;
            }
            receiveEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onStickyEventBusCome(BaseEvent event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(BaseEvent event) {

    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(BaseEvent event) {

    }

    public void showLoadingDialog(String msg) {
        if (mLoadingDialog == null) {
            mLoadingDialog = new LoadingDialog(this);
        }
        if (StringUtils.isNotEmpty(msg)) {
            mLoadingDialog.setMessage(msg);
        }
        mLoadingDialog.show();
    }

    public void dismissLoadingDialog() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }



    public void showDialog(String msg) {
        if (showDialog == null) {
            showDialog = new ShowDialog(this);
        }
        if (StringUtils.isNotEmpty(msg)) {
            showDialog.setMessage(msg);
        }
        showDialog.show();
    }

    public void showDialog(String msg, int resource) {
        if (showDialog == null) {
            showDialog = new ShowDialog(this);
        }
        if (StringUtils.isNotEmpty(msg)) {
            showDialog.setMessage(msg);
            showDialog.setResource(resource);
        }
        showDialog.show();
    }

    public void dismissShowDialog() {
        if (showDialog != null && showDialog.isShowing()) {
            showDialog.dismiss();
        }
    }


    public void toast(String strMsg) {
        ToastUtils.showShort(this, strMsg);
    }

    public void launch(Class clazz) {
        Intent intent = new Intent(this, clazz);
        intent.putExtras(new Bundle());
        startActivity(intent);
    }

    public void launch(Class clazz, Bundle bundle) {
        Intent intent = new Intent(this, clazz);
        intent.putExtras(bundle);
        startActivity(intent);
    }





    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        Configuration configuration = new Configuration();
        configuration.setToDefaults();
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return resources;
    }

    private void checkWriteSettingsPermission(int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(this)) {
                CommonDialog dialog = new CommonDialog(this, "我们的应用需要您授权\"修改系统设置\"的权限,请点击\"设置\"确认开启?",
                        "取消", "去设置",
                        view -> {
                            finish();
                        }, view1 -> {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS, Uri.parse(
                            "package:" + getPackageName()));
                    startActivityForResult(intent, requestCode);
                });
                dialog.setCancelable(false);
                dialog.show();
            }
        }
    }

    /**
     * 软键盘处理，点击外部，软键盘收起来
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (AppUtils.isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }

            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public static BaseActivity getInstance() {
        return instance;
    }


    /**
     * 初始化沉浸式
     * Init immersion bar.
     */
    protected void initImmersionBar() {
        //设置共同沉浸式样式
        ImmersionBar.with(this)
                //.hideBar(BarHide.FLAG_HIDE_BAR)
                .init();
    }

}

